package admin

import (
	"duoke/model"
	"duoke/service"
	"duoke/utils/gconv"
	"duoke/utils/gstr"
	"duoke/utils/response"
	"duoke/utils/valid"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"github.com/syyongx/php2go"
)

var GoodsAccount = new(goodsAccountCtl)

type goodsAccountCtl struct{}

// 账户保存
func (ctl *goodsAccountCtl) Save(c *gin.Context) {
	accountR, _ := service.Request.Account(c)
	var req model.ReqGoodsAccount
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, valid.GetError(err.(validator.ValidationErrors), req), nil)
		return
	}
	// 过期时间预处理
	req.ExpireTime = gconv.Int64(gstr.SubStr(gconv.String(req.ExpireTime), 0, 10))
	req.BindGoodsIds = php2go.Implode(",", req.GoodsIds)
	req.Role = "goods"
	req.UseStorageAcid = accountR.Id
	req.Pid = accountR.Id
	// 保存数据
	err := service.GoodsAccount.Save(c, req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "保存成功", nil)
}

// 账户列表
func (ctl *goodsAccountCtl) List(c *gin.Context) {
	var req model.ReqList
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	list, total, err := service.GoodsAccount.List(c, req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "", gin.H{"total": total, "list": list})
}

// 账户删除
func (ctl *goodsAccountCtl) Del(c *gin.Context) {
	var req model.ReqIds
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, valid.GetError(err.(validator.ValidationErrors), req), nil)
		return
	}
	err := service.GoodsAccount.Del(req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "删除成功", nil)
}

// 账户状态
func (ctl *goodsAccountCtl) State(c *gin.Context) {
	var req model.ReqId
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, valid.GetError(err.(validator.ValidationErrors), req), nil)
		return
	}
	err := service.GoodsAccount.State(req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "操作成功", nil)
}
